package cn.wh.beans.factory.support;

import cn.wh.BeansException;
import cn.wh.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @author: wh
 * @create: 2022-08-17 16:03
 * @description
 **/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean=createBeanInstance(beanDefinition,beanName,args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //注册到单例bean容器
        addSingleton(beanName, bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor<?> ctor : declaredConstructors) {
            //这里只进行了参数个数与实例化个数是否相同 并没有进行 参数类型是否符合 在 boot 是进行了参数类型的判断
            if (args!=null&&ctor.getParameterTypes().length==args.length){
                constructor=ctor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition,beanName,constructor,args);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
